package com.dries.netty.chat.controller;

import cn.hutool.core.collection.CollUtil;
import com.dries.netty.chat.entity.User;
import com.dries.netty.chat.session.SessionMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Dries
 * @email 1451691457@qq.com
 */
@RestController
@RequestMapping("/ws")
@Slf4j
public class SocketController {

    public static Map<Long, String> img = new ConcurrentHashMap<>();


    /**
     * 获取房间里的用户
     */
    @GetMapping("/online/{room}")
    public Map<String, Object> online(@PathVariable String room) {

        Map<String, Object> result = new HashMap<>();

        Set<User> rooms = SessionMap.getSingleInstance().getGroupUsers(room);

        List<Map<String, String>> users = new ArrayList<>();

        if (CollUtil.isNotEmpty(rooms)) {
            rooms.forEach(user -> {
                Map<String, String> map = new HashMap<>();
                map.put("nick", user.getNickName());
                map.put("id", user.getUserId());
                users.add(map);
            });

            result.put("onlineNum", 0);
            result.put("onlineUsera", users);
        } else {
            result.put("onlineNum", 0);
            result.put("onlineUsera", null);
        }

        return result;
    }

    /**
     * 判断昵称在某个房间中是否已存在，房间是否有密码，如果有，用户输入的密码又是否正确
     *
     * @param room     房间号
     * @param nickName 用户名
     * @param pwd      房间密码
     * @return
     */
    @PostMapping("/judgeNick")
    public Map<String, Object> judgeNick(String room, String nickName, String pwd) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        Set<User> rooms = SessionMap.getSingleInstance().getGroupUsers(room);

        if (CollUtil.isNotEmpty(rooms)) {
            rooms.forEach(user -> {
                if (user.getNickName().equals(nickName)) {
                    result.put("code", 1);
                    result.put("msg", "昵称已存在，请重新输入");
                    log.debug("有重复");
                }
            });

            if ((Integer) result.get("code") != 0) {
                return result;
            }
            result.put("code", 3);
            result.put("msg", "房间无密码");
            return result;
        }

        return result;
    }

    /**
     * 获取所有房间
     *
     * @return
     */
    @GetMapping("/allRoom")
    public Map<String, Object> allRoom() {
        Map<String, Object> result = new HashMap<>();
        List<String> rooms = SessionMap.getSingleInstance().getGroupNames();
        result.put("rooms", rooms);
        return result;
    }

}
